<template>
  <div class="toc">
    <div class="toc-content">
      <div v-if="tocList" class="toc-title">- 目录 -</div>
      <blog-toc-ul :list-data="listRef"></blog-toc-ul>
    </div>
  </div>
</template>

<script>
import blogTocUl from "./blog-toc-ul.vue";
import {computed, defineComponent} from "vue";


export default defineComponent({
  name: "blog-toc",
  components: {
    "blog-toc-ul": blogTocUl
  },
  props: {
    tocList: {
      type: Object,
      require: true
    },
    activeAnchor: String,
    autoCollapse: Boolean
  },
  setup(props) {

    let treeContains = (tree, anchor) => {
      for (const item of tree.items) {
        if (item.anchor === anchor) {
          return true;
        }
        if (item.children) {
          if (treeContains(item.children, anchor)) {
            return true;
          }
        }
      }
      return false;
    }

    let toggleCollapse = (tree, anchor) => {
      let res = false;
      tree.items.forEach((item) => {
        if (item.children) {
          let temp = toggleCollapse(item.children, anchor);
          res = res || temp;
        }
        item.active = (item.anchor === anchor);
        res = res || item.active;
      });
      tree.show = res;
      return res;
    };

    const listRef = computed(() => {
      let hasA = treeContains(props.tocList, props.activeAnchor);
      if (hasA) {
        toggleCollapse(props.tocList, props.activeAnchor);
      }
      return props.tocList;
    });

    return {
      listRef
    };
  }
})
</script>

<style scoped>

</style>